var uuid = require("uuid")
var roomPlayerCount = 2		//房间人数
var roomMaxSpeed = 30		//最大同时生成速度
var roomTimeout = 1200000  	//房间超时时间
var matchTimeout = 20000	//匹配超时时间
var bearcat = require("bearcat")
var gameTypeRooms = {
	"default" : "defaultRoom",
	"epidemic" : "epidemicRoom",
	"nhwEpidemic" : "nhwRoom"
}
//匹配模块
var matchServer = function(app) {
	this.app = app
	this.channelService = this.app.get('channelService')
	this.matchType = {}
	this.userType = {}
	this.matchUsers = {}
	this.userMaps = {}
	this.roomList = {}
}
matchServer.prototype.init = function() {
	console.log("matchServer init")
	setInterval(this.update.bind(this),500)
}
//update
matchServer.prototype.update = function() {
	var curTime = Date.now()
	for(var gameType in this.matchType){
		//检测匹配成功
		var list = []
		for(var uid in this.matchType[gameType]){
			if((this.matchUsers[uid] + 1000) < curTime){
				list.push(uid)
			}
		}
		var curCount = 0
		while(list.length >= roomPlayerCount && curCount < roomMaxSpeed){
			curCount++
			this.matchSuccess(list.splice(0,2))
		}
	}
	//清除过期房间
	for(var roomId in this.roomList){
		if((this.roomList[roomId].createTime + roomTimeout) < curTime){
			this.finishRoom(roomId)
		}
	}
	//清除时间过长
	var notify = {
		type : "matchTimeout"
	}
	for(var uid in this.matchUsers){
		if((this.matchUsers[uid] + matchTimeout) < curTime){
			delete this.matchUsers[uid]
			let gameType = this.userType[uid]
			delete this.matchType[gameType][uid]
			delete this.userType[uid]
			this.sendToUser(uid,notify)
		}
	}
}
//加入匹配
matchServer.prototype.joinMatch = function(uid,gameType,cb) {
	if(this.matchUsers[uid]){
		cb(false,"已在匹配中")
		return
	}
	if(this.userMaps[uid]){
		cb(false,"已在房间中")
		return
	}
	if(!this.matchType[gameType])
		this.matchType[gameType] = {}
	this.matchType[gameType][uid] = true
	this.userType[uid] = gameType
	this.matchUsers[uid] = Date.now()
	cb(true)
}
//离开匹配
matchServer.prototype.leaveMatch = function(uid,cb) {
	if(!this.matchUsers[uid]){
		var err = "不在匹配中"
		if(this.userMaps[uid]){
			err = "已匹配成功"
		}
		cb(false,err)
		return
	}
	delete this.matchUsers[uid]
	let gameType = this.userType[uid]
	delete this.matchType[gameType][uid]
	delete this.userType[uid]
	cb(true)
}
//关闭匹配房间
matchServer.prototype.closeRoom = function(uid,cb) {
	var roomId = this.userMaps[uid]
	if(!roomId){
		cb(false,"不在房间中")
		return
	}
	this.finishRoom(roomId)
	cb(true)
}
//发送消息
matchServer.prototype.sendMessage = function(uid,text,cb) {
	var roomId = this.userMaps[uid]
	if(!roomId){
		cb(false,"不在房间中")
		return
	}
	if(typeof(text) != "string"){
		cb(false,"text must is string")
		return
	}
	var notify = {
		type : "userMessage",
		uid : uid,
		text : text
	}
	if(!this.roomList[roomId]){
		console.error("找不到玩家房间",roomId)
		cb(false,"system error")
		return
	}
	this.roomList[roomId].sendToRoom(notify)
	cb(true)
}
//保存房间数据
matchServer.prototype.saveRoomData = function(uid,key,value,cb) {
	var roomId = this.userMaps[uid]
	if(!roomId){
		cb(false,"不在房间中")
		return
	}
	if(typeof(key) !== "string" || (typeof(value) != "string" && typeof(value) != "number")){
		cb(false,"args type error")
		return
	}
	if(!this.roomList[roomId]){
		console.error("找不到玩家房间",roomId)
		cb(false,"system error")
		return
	}
	this.roomList[roomId].saveRoomData(key,value)
	cb(true)
}
//获取房间数据
matchServer.prototype.getRoomData = function(uid,cb) {
	var roomId = this.userMaps[uid]
	if(!roomId){
		cb(false,"不在房间中")
		return
	}
	if(!this.roomList[roomId]){
		console.error("找不到玩家房间",roomId)
		cb(false,"system error")
		return
	}
	let roomData = this.roomList[roomId].getRoomData()
	cb(true,roomData)
}
//创建匹配房间
matchServer.prototype.matchSuccess = function(uidArr) {
	let roomId = uuid.v1()
	let gameType = this.userType[uidArr[0]]
	let roomType = gameTypeRooms[gameType] || gameTypeRooms["default"]
	let room = bearcat.getBean(roomType,this,this.app,uidArr,roomId)
	room.roomId = roomId
	this.roomList[room.roomId] = room
	for(var i = 0;i < uidArr.length;i++){
		this.userMaps[uidArr[i]] = roomId
		delete this.matchUsers[uidArr[i]]
		delete this.matchType[gameType][uidArr[i]]
		delete this.userType[uidArr[i]]
	}
}
//结束房间
matchServer.prototype.finishRoom = function(roomId) {
	if(this.roomList[roomId]){
        for(var i = 0;i < this.roomList[roomId].uidArr.length;i++){
            var uid = this.roomList[roomId].uidArr[i]
            delete this.userMaps[uid]
        }
		this.roomList[roomId].closeRoom()
		delete this.roomList[roomId]
	}
}
//玩家断线
matchServer.prototype.userleave = function(uid) {
	var roomId = this.userMaps[uid]
	if(roomId){
		this.roomList[roomId].userleave(uid)
	}else if(this.matchUsers[uid]){
		delete this.matchUsers[uid]
	}
}
//玩家登录
matchServer.prototype.userLogin = function(uid) {
	var roomId = this.userMaps[uid]
	if(roomId){
		this.roomList[roomId].userLogin(uid)
	}
}
//发送消息给玩家
matchServer.prototype.sendToUser = function(uid,notify) {
	this.channelService.pushMessageByUids('onMessage', notify, [{
      uid: uid,
      sid: this.app.serverId
    }])
}
//发送消息到房间
matchServer.prototype.sendToRoom = function(roomId,notify) {
	if(!this.roomList[roomId])
		return
	this.roomList[roomId].sendToRoom(notify)
}
//房间指令
matchServer.prototype.roomCmd = function(uid,msg,cb) {
	var cmd = msg.cmd
	var roomId = this.userMaps[uid]
	if(!this.roomList[roomId]){
		cb(false,"不在房间中")
		return
	}
	if(!this.roomList[roomId][cmd]){
		cb(false,"指令错误")
		return
	}
	this.roomList[roomId][cmd](uid,msg,cb)
}
module.exports = {
	id : "matchServer",
	func : matchServer,
	scope : "prototype",
	init : "init",
	args : [{
		name : "app",
		type : "Object"
	}],
	props : [{
		name : "redisDao",
		ref : "redisDao"
	}]
}